<?php

function helper_redirectTop($url) {
    echo "<script type='text/javascript'>";
    echo "window.top.location.href = '" . $url . "'";
    echo "</script>";
    exit;
}function helper_redirect($url) {    echo "<script type='text/javascript'>";    echo "window.location.href = '" . $url . "'";    echo "</script>";    exit;}

function helper_checkUserLogin($facebook, $fbConfig) {
    $uid = $facebook->getUser();

    $islogin = true;
    if ($uid) {
        try {
            $permits = $facebook->api('/me/permissions');
            if (true === isset($permits['data'][0])) {
                $permits = array_keys($permits['data'][0]);
                $scopes = explode(',', $fbConfig['fbScope']);
                foreach ($scopes as $scope) {
                    $scope = trim($scope);
                    if (true !== in_array($scope, $permits)) {
                        $islogin = false;
                        break;
                    }
                }
            }
        } catch (FacebookApiException $e) {
            echo $e->getMessage();
            $islogin = false;
        }
    } else {
        $islogin = false;
    }
    if (!$islogin) {
        $config = array();
        $config['scope'] = $fbConfig['fbScope'];
        $config['redirect_uri'] = $fbConfig['redirect_uri'];
        $config['display'] = 'page';
        $login_url = $facebook->getLoginUrl($config);
        //echo $login_url;
        helper_redirectTop($login_url);
    }
    return $islogin;
}

function object2Array($d) {
    if (is_object($d)) {
        $d = get_object_vars($d);
    }

    if (is_array($d)) {
        return array_map(__FUNCTION__, $d);
    } else {
        return $d;
    }
}

function helper_processMatching($access_token, $controller) {
    $PointsArray = array();
    $FriendInfo = array();
    $FriendofFriends = array();
    $UserId = "";
    $UserId = $controller->facebook->getUser();

    $FriendLikes = $controller->getDataLikes();
    //get all access token of users in database who are friends of current user
    $StringFbusers = array();
    foreach ($FriendLikes as $friend) {
        $StringFbusers[] = $friend['uid'];
    }
    // get friend of friend like
    $FriendofFriends = $controller->user->getAllAccessToken($StringFbusers);
    //create batch request to request all query to facebook.
    $Queries = array();
    $QueryArray = array('method' => 'GET', 'relative_url' => '/me?fields=id,books,music,movies,name,gender,birthday');
    $Queries[] = $QueryArray;
    foreach ($FriendofFriends as $item) {
        $query = "SELECT books,movies,music,uid,sex,birthday_date,name FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1 = me())";
        $query = urlencode('method/fql.query?access_token=' . $item->access_token . '&query=' . $query);
        $QueryArray = array('method' => 'GET', 'relative_url' => $query);
        //echo 'method/fql.query?query=' . str_replace(' ', '+', $query)."&access_token=".$item->access_token."<br/>";
        $Queries[] = $QueryArray;
    }
    $FriendOfFriendLikes = $controller->facebook->api('/?batch=' . json_encode($Queries), 'POST');
    //get info of logined user
    $UserLikes = object2Array(json_decode($FriendOfFriendLikes[0]['body']));

    $UserBooks = array();
    $UserMovies = array();
    $UserMusics = array();
    //print_r($FriendLikes);
    if (isset($UserLikes['books'])) {
        $UserBooks = $UserLikes['books']['data'];
    }
    if (isset($UserLikes['movies'])) {
        $UserMovies = $UserLikes['movies']['data'];
    }
    if (isset($UserLikes['music'])) {
        $UserMusics = $UserLikes['music']['data'];
    }
    foreach ($FriendOfFriendLikes as $index => $item) {
        if ($index == 0) {
            continue;
        }
        $FriendLikes = array_merge($FriendLikes, object2Array(json_decode($item['body'])));
    }

    //print_r($objs);
    //  echo $CurrentDay;

    foreach ($FriendLikes as $index => $friend) {

        if (is_array($friend)) {
            //print_r($friend);
            if (isset($friend['uid'])) {
                $friend['uid'] = number_format($friend['uid'], 0, '', '');
                if ($friend['uid'] == $UserId) {
                    continue;
                }
                if (isset($PointsArray[$friend['uid']]))
                    continue;

                $PointsArray[$friend['uid']] = 0;
                $PointsBooksArray[$friend['uid']] = 0;
                $PointsMoviesArray[$friend['uid']] = 0;
                $PointsMusicArray[$friend['uid']] = 0;

                $FriendInfo[$friend['uid']] = array();
                $FriendInfo[$friend['uid']]['sex'] = $friend['sex'];
                $FriendInfo[$friend['uid']]['name'] = $friend['name'];
                $FriendInfo[$friend['uid']]['books'] = "";
                $FriendInfo[$friend['uid']]['movies'] = "";
                $FriendInfo[$friend['uid']]['music'] = "";
                $FriendInfo[$friend['uid']]['friend_books'] = "";
                $FriendInfo[$friend['uid']]['friend_music'] = "";
                $FriendInfo[$friend['uid']]['friend_movies'] = "";

                $numberCate = 0;
                //matching books
                $checkCate = 0;
                if (count($UserBooks) > 0 && $friend['books'] != "") {
                    $FriendInfo[$friend['uid']]['friend_books'] = $friend['books'];
                    foreach ($UserBooks as $item) {
                        if (is_numeric(strpos($friend['books'], $item['name']))) {
                            if ($checkCate == 0) {
                                $numberCate++;
                                $checkCate = 1;
                            }
                            $FriendInfo[$friend['uid']]['books'] .= $item['name'] . ",";
                            if ($item['category'] == "Book") {
                                $PointsArray[$friend['uid']]++;
                                $PointsBooksArray[$friend['uid']]++;
//                                if ($friend['uid'] == '100004061363829')
//                                    echo $item['name'] . "1<br/>";
                            } else {
                                $PointsArray[$friend['uid']]+=0.2;
                                $PointsBooksArray[$friend['uid']]+=0.2;
//                                if ($friend['uid'] == '100004061363829')
//                                    echo $item['name'] . "0.2<br/>";
                            }
                        };
                    }
                }
                //matching movies
                $checkCate = 0;
                if (count($UserMovies) > 0 && $friend['movies'] != "") {
                    $FriendInfo[$friend['uid']]['friend_movies'] = $friend['movies'];
                    foreach ($UserMovies as $item) {
                        if (is_numeric(strpos($friend['movies'], $item['name']))) {
                            if ($checkCate == 0) {
                                $numberCate++;
                                $checkCate = 1;
                            }
                            $FriendInfo[$friend['uid']]['movies'] .= $item['name'] . ",";
//                            if ($friend['uid'] == '100004061363829')
//                                echo $item['name'] . "1<br/>";
                            $PointsArray[$friend['uid']]++;
                            $PointsMoviesArray[$friend['uid']]++;
                        };
                    }
                }
                $checkCate = 0;
                //matching music
                if (count($UserMusics) > 0 && $friend['music'] != "") {
                    $FriendInfo[$friend['uid']]['friend_music'] = $friend['music'];
                    foreach ($UserMusics as $item) {
                        //print_r($item);
                        //echo $friend['music']." ".$item['name']." ".strpos($friend['music'], $item['name'])."<br/>";
                        if (is_numeric(strpos($friend['music'], $item['name']))) {
                            if ($checkCate == 0) {
                                $numberCate++;
                                $checkCate = 1;
                            }
                            $FriendInfo[$friend['uid']]['music'] .= $item['name'] . ",";
//                            if ($friend['uid'] == '100004061363829')
//                                echo $item['name'] . "1<br/>";
                            $PointsArray[$friend['uid']]++;
                            $PointsMusicArray[$friend['uid']]++;
                        };
                    }
                }
                //check number cate matching

                if ($numberCate == 2) {
                    $PointsArray[$friend['uid']] *=1.5;
//                    if ($friend['uid'] == '100004061363829')
//                        echo $numberCate . " 1.5<br/>";
                }
                if ($numberCate == 3) {
                    $PointsArray[$friend['uid']] *=2;
//                    if ($friend['uid'] == '100004061363829')
//                        echo $numberCate . " 2<br/>";
                }

                //check sex matching
                if ($UserLikes['gender'] == $friend['sex']) {
                    $PointsArray[$friend['uid']] *=1.5;
                    $PointsBooksArray[$friend['uid']]*=1.5;
                    $PointsMoviesArray[$friend['uid']]*=1.5;
                    $PointsMusicArray[$friend['uid']]*=1.5;

//                    if ($friend['uid'] == '100004061363829')
//                        echo $UserLikes['gender'] . " 1.5<br/>";
                } else {
                    if ($friend['sex'] != "") {
                        $PointsArray[$friend['uid']] *=1.2;
                        $PointsBooksArray[$friend['uid']]*=1.2;
                        $PointsMoviesArray[$friend['uid']]*=1.2;
                        $PointsMusicArray[$friend['uid']]*=1.2;

//                        if ($friend['uid'] == '100004061363829')
//                            echo $UserLikes['gender'] . " 1.2<br/>";
                    }
                }
                //check age matching
                $UserAge = $controller->getAge($UserLikes['birthday']);
                if ($friend['birthday_date'] != "") {
                    $FriendInfo[$friend['uid']]['birthday_date'] = $friend['birthday_date'];
                    $friendAge = $controller->getAge($friend['birthday_date']);
                    if ($friendAge > 0) {
                        $FriendInfo[$friend['uid']]['age'] = $friendAge;
                        $rangeAge = abs($UserAge - $friendAge);
                        if ($rangeAge <= 10) {
                            $PointsArray[$friend['uid']]*=1.5;
                            $PointsBooksArray[$friend['uid']]*=1.5;
                            $PointsMoviesArray[$friend['uid']]*=1.5;
                            $PointsMusicArray[$friend['uid']]*=1.5;

//                            if ($friend['uid'] == '100004061363829')
//                                echo $UserAge . " 1.5<br/>";
                        } else {
                            $PointsArray[$friend['uid']]*=1.2;
                            $PointsBooksArray[$friend['uid']]*=1.2;
                            $PointsMoviesArray[$friend['uid']]*=1.2;
                            $PointsMusicArray[$friend['uid']]*=1.2;

//                            if ($friend['uid'] == '100004061363829')
//                                echo $UserAge . " 1.2<br/>";
                        }
                    } else {
                        $FriendInfo[$friend['uid']]['age'] = "";
                    }
                } else {
                    $FriendInfo[$friend['uid']]['birthday_date'] = "";
                    $FriendInfo[$friend['uid']]['age'] = "";
                }
            } else {
                //print_r($friend) . "<br/>";
            }
        } else {
            //echo $friend . "<br/>";
        }
    }
    arsort($PointsArray);
    arsort($PointsBooksArray);
    arsort($PointsMoviesArray);
    arsort($PointsMusicArray);
    
    $DataResult = array();
    $DataResult['points'] = $PointsArray;
    $DataResult['pointsbooks'] = $PointsBooksArray;
    $DataResult['pointsmovies'] = $PointsMoviesArray;
    $DataResult['pointsmusic'] = $PointsMusicArray;
    
    $DataResult['FriendInfo'] = $FriendInfo;
    return $DataResult;
}